<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">商品详情</text>
      <view class="nav-share" @click="openShareMenu">
        <uni-icons type="more-filled" size="20" color="#333"></uni-icons>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载商品信息中...</text>
    </view>
    
    <!-- 商品内容 -->
    <block v-else>
      <!-- 商品图片 -->
      <swiper class="product-swiper" indicator-dots autoplay circular indicator-color="rgba(255,255,255,0.4)" indicator-active-color="#FF8C42">
        <swiper-item>
          <image :src="imageFullUrl(product.mainImageUrl)" mode="aspectFill" class="product-image"></image>
        </swiper-item>
      </swiper>
      
      <!-- 商品信息 -->
      <view class="product-info">
        <view class="product-status" v-if="product.status === 0">已下架</view>
        <view class="product-status stock-warning" v-else-if="product.totalStock <= product.safeStock">库存紧张</view>
        
        <view class="product-price">¥ {{ parseFloat(product.price || 0).toFixed(2) }}</view>
        <view class="product-name">{{ product.name }}</view>
        <view class="product-desc">{{ product.description }}</view>
        
        <view class="product-meta">
          <view class="meta-item">
            <text class="meta-label">库存:</text>
            <text class="meta-value">{{ product.totalStock }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">分类:</text>
            <text class="meta-value">{{ getCategoryName(product.categoryId) }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">商品编号:</text>
            <text class="meta-value">{{ product.id }}</text>
          </view>
        </view>
      </view>
      
      <!-- 数量选择 -->
      <view class="quantity-section">
        <view class="section-title">数量</view>
        <view class="quantity-wrapper">
          <uni-number-box 
            v-model="quantity" 
            :min="1" 
            :max="product.totalStock || 99"
            :disabled="product.status === 0 || product.totalStock <= 0"
            background="#FFF9F2"
            color="#FF8C42"
          ></uni-number-box>
          <text class="stock-info">库存: {{ product.totalStock || 0 }}</text>
        </view>
      </view>
      
      <!-- 商品详情 -->
      <view class="detail-section">
        <view class="section-title">商品详情</view>
        <view class="detail-content">
          <rich-text :nodes="detailContent"></rich-text>
        </view>
      </view>
    </block>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="action-left">
        <view class="action-btn" @click="goToHome">
          <uni-icons type="home" size="24" color="#666"></uni-icons>
          <text>首页</text>
        </view>
        <view class="action-btn" @click="goToCart">
          <uni-icons type="cart" size="24" color="#666"></uni-icons>
          <text>购物车</text>
        </view>
      </view>
      <view class="action-right">
        <button 
          class="add-cart-btn" 
          @click="addToCart"
          :disabled="product.status === 0 || product.totalStock <= 0"
          :class="{ 'btn-disabled': product.status === 0 || product.totalStock <= 0 }"
        >加入购物车</button>
        <button 
          class="buy-btn" 
          @click="buyNow"
          :disabled="product.status === 0 || product.totalStock <= 0"
          :class="{ 'btn-disabled': product.status === 0 || product.totalStock <= 0 }"
        >立即购买</button>
      </view>
    </view>
    
    <!-- 分享菜单 -->
    <uni-popup ref="sharePopup" type="bottom">
      <view class="share-menu">
        <view class="share-title">分享商品</view>
        <view class="share-options">
          <view class="share-option" @click="shareToWechat">
            <view class="share-icon wechat">
              <uni-icons type="weixin" size="30" color="#fff"></uni-icons>
            </view>
            <text>微信</text>
          </view>
          <view class="share-option" @click="shareToMoments">
            <view class="share-icon moments">
              <uni-icons type="pyq" size="30" color="#fff"></uni-icons>
            </view>
            <text>朋友圈</text>
          </view>
          <view class="share-option" @click="shareToQQ">
            <view class="share-icon qq">
              <uni-icons type="qq" size="30" color="#fff"></uni-icons>
            </view>
            <text>QQ</text>
          </view>
          <view class="share-option" @click="copyLink">
            <view class="share-icon link">
              <uni-icons type="link" size="30" color="#fff"></uni-icons>
            </view>
            <text>复制链接</text>
          </view>
        </view>
        <button class="share-cancel" @click="closeShareMenu">取消</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useProductStore } from '@/store/product.js';
import { useCartStore } from '@/store/cart.js';
import { useUserStore } from '@/store/user.js';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { getImageUrl } from '@/config/env';
import { buyNowService } from '@/utils/payment/buy-now-service.js';
//import uni from 'uni-app'; // Declare the uni variable

// 状态栏高度
const statusBarHeight = ref(0);

// 商品ID
const productId = ref(null);

// 商品数量
const quantity = ref(1);

// 分享菜单引用
const sharePopup = ref(null);

// 加载状态
const loading = ref(true);

// 商品状态管理
const productStore = useProductStore();
// 购物车状态管理
const cartStore = useCartStore();
// 用户状态管理
const userStore = useUserStore();

// 商品数据
const product = ref({
  id: 0,
  name: '加载中...',
  description: '加载中...',
  price: 0,
  categoryId: 0,
  totalStock: 0,
  safeStock: 0,
  status: 1,
  mainImageUrl: '/static/placeholder.png',
  merchantId: 0,
  createTime: null,
  updateTime: null
});

// 商品详情内容
const detailContent = computed(() => {
  if (!product.value.description) return '<p>暂无详情</p>';
  
  // 将商品描述转换为HTML格式
  return `
    <div style="padding: 10px;">
      <p style="font-size: 28rpx; color: #666; line-height: 1.6;">${product.value.description}</p>
      <p style="font-size: 28rpx; color: #666; margin-top: 20rpx;">商品编号: ${product.value.id}</p>
      <p style="font-size: 28rpx; color: #666;">分类: ${getCategoryName(product.value.categoryId)}</p>
      <p style="font-size: 28rpx; color: #666;">库存: ${product.value.totalStock}</p>
    </div>
  `;
});

// 获取分类名称
const getCategoryName = (categoryId) => {
  const categoryMap = {
    1: '水果',
    2: '零食',
    3: '饮料',
    4: '速食',
    5: '日用品',
    6: '个人护理'
  };
  
  return categoryMap[categoryId] || '未分类';
};

// 生成完整的图片 URL - 使用统一的工具函数
const imageFullUrl = getImageUrl;

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 跳转到首页
const goToHome = () => {
  uni.redirectTo({
  	url :'/pages/index/index' 
  })
};

// 跳转到购物车
const goToCart = () => {
  uni.redirectTo({
    url: '/pages/cart/index'
  });
};

// 加入购物车
const addToCart = async () => {
  // 检查用户是否登录
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  // 检查商品状态和库存
  if (product.value.status === 0) {
    uni.showToast({
      title: '该商品已下架',
      icon: 'none'
    });
    return;
  }
  
  if (product.value.totalStock <= 0) {
    uni.showToast({
      title: '该商品库存不足',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 使用购物车 store 的 addToCart 方法
    const result = await cartStore.addToCart(product.value, quantity.value);
    
    // 如果添加成功，可以在这里做一些额外的操作
    if (result) {
      console.log(`已加入购物车：${quantity.value}件`);
    }
  } catch (error) {
    console.error('添加购物车失败:', error);
    uni.showToast({
      title: '添加购物车失败，请重试',
      icon: 'none'
    });
  }
};

// 立即购买 - 使用新的立即购买服务
const buyNow = async () => {
  try {
    const result = await buyNowService.buyNow(product.value, quantity.value, '商品详情页立即购买');
    
    if (result.success) {
      console.log('立即购买成功，订单号:', result.orderNo);
    }
  } catch (error) {
    console.error('立即购买失败:', error);
    // 错误已在服务中处理，这里不需要额外处理
  }
};

// 打开分享菜单
const openShareMenu = () => {
  sharePopup.value.open();
};

// 关闭分享菜单
const closeShareMenu = () => {
  sharePopup.value.close();
};

// 分享到微信
const shareToWechat = () => {
  uni.showToast({
    title: '分享到微信功能待实现',
    icon: 'none'
  });
  closeShareMenu();
};

// 分享到朋友圈
const shareToMoments = () => {
  uni.showToast({
    title: '分享到朋友圈功能待实现',
    icon: 'none'
  });
  closeShareMenu();
};

// 分享到QQ
const shareToQQ = () => {
  uni.showToast({
    title: '分享到QQ功能待实现',
    icon: 'none'
  });
  closeShareMenu();
};

// 复制链接
const copyLink = () => {
  const link = `https://yourapp.com/product/${product.value.id}`;
  uni.setClipboardData({
    data: link,
    success: () => {
      uni.showToast({
        title: '链接已复制',
        icon: 'success'
      });
    }
  });
  closeShareMenu();
};

// 加载商品数据的函数
const loadProductData = () => {
	console.log("商品id",productId.value);
  if (productId.value) {
    console.log('开始加载商品数据，ID:', productId.value);
    
    // 打印当前商品列表，用于调试
    productStore.debugState();
    
    // 方法1: 从状态管理中获取当前选中的商品
    if (productStore.currentProduct && productStore.currentProduct.id === parseInt(productId.value)) {
      product.value = productStore.currentProduct;
      console.log('从状态管理中获取当前商品:', product.value);
      loading.value = false;
    } 
    // 方法2: 从状态管理中的商品列表中查找
    else {
      const foundProduct = productStore.getProductById(productId.value);
      if (foundProduct) {
        product.value = foundProduct;
        console.log('从商品列表中查找到商品:', product.value);
        loading.value = false;
      } else {
        console.error('未找到商品数据，ID:', productId.value);
        
        uni.showToast({
          title: '未找到商品数据',
          icon: 'none'
        });
        loading.value = false;
      }
    }
  } else {
    console.error('未找到商品ID');
    uni.showToast({
      title: '商品ID不存在',
      icon: 'none'
    });
    loading.value = false;
  }
};

// 正确使用 onLoad 生命周期
onLoad((options) => {
  console.log('页面参数:', options);
  const id = parseInt(options.id);
  if (isNaN(id)) {
    uni.showToast({ title: '商品ID无效', icon: 'none' });
    return;
  }
  productId.value = id; // 设置 productId
  loadProductData(); // 调用数据加载函数
  
  // 获取系统信息
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
  }
  
  // 初始化用户状态
  userStore.initUserState();
  
  // 获取购物车数量
  cartStore.fetchCartList();
  cartStore.getCartCount();
});

// 每次显示页面时刷新数据
onShow(() => {
  console.log('商品详情页显示，重新初始化用户状态');
  // 重新初始化用户状态，确保从其他页面跳转回来时能正确获取登录状态
  userStore.initUserState();
  // 刷新购物车数据
  cartStore.fetchCartList();
  cartStore.getCartCount();
});
</script>

<style>
.container {
  padding-bottom: 100rpx;
  background-color: #FFF9F2;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  position: relative;
  z-index: 100;
}

.nav-back, .nav-share {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #FFE6CC;
  border-top: 6rpx solid #FF8C42;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 商品图片 */
.product-swiper {
  width: 100%;
  height: 750rpx;
}

.product-image {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

/* 商品信息 */
.product-info {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  position: relative;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.product-status {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  background-color: #999;
  color: white;
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

.stock-warning {
  background-color: #FF9F1C;
}

.product-price {
  font-size: 40rpx;
  color: #FF8C42;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.product-name {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.product-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.product-meta {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx dashed #FFE6CC;
}

.meta-item {
  margin-right: 30rpx;
  margin-bottom: 10rpx;
}

.meta-label {
  font-size: 24rpx;
  color: #999;
  margin-right: 10rpx;
}

.meta-value {
  font-size: 24rpx;
  color: #666;
}

/* 数量选择 */
.quantity-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  margin: 0 20rpx 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  border-left: 6rpx solid #FF8C42;
  padding-left: 20rpx;
}

.quantity-wrapper {
  display: flex;
  align-items: center;
}

.stock-info {
  margin-left: 20rpx;
  font-size: 24rpx;
  color: #999;
}

/* 商品详情 */
.detail-section {
  padding: 30rpx;
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.detail-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

/* 底部操作栏 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  border-top: 1rpx solid #FFE6CC;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.action-left {
  display: flex;
  width: 30%;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 50%;
}

.action-btn text {
  font-size: 22rpx;
  color: #666;
  margin-top: 6rpx;
}

.action-right {
  display: flex;
  width: 70%;
}

.add-cart-btn, .buy-btn {
  flex: 1;
  height: 100rpx;
  line-height: 100rpx;
  text-align: center;
  font-size: 28rpx;
  border-radius: 0;
}

.add-cart-btn {
  background-color: #FF9F1C;
  color: #fff;
}

.buy-btn {
  background-color: #FF8C42;
  color: #fff;
}

.btn-disabled {
  background-color: #ccc;
  color: #fff;
}

/* 分享菜单 */
.share-menu {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
}

.share-title {
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.share-options {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
}

.share-option {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.share-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.wechat {
  background-color: #07C160;
}

.moments {
  background-color: #50B674;
}

.qq {
  background-color: #12B7F5;
}

.link {
  background-color: #FF8C42;
}

.share-option text {
  font-size: 24rpx;
  color: #666;
}

.share-cancel {
  margin-top: 30rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  background-color: #f5f5f5;
  color: #333;
  font-size: 28rpx;
}
</style>
